package com.ncloud.system.controller;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.body.Result;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.ResultUtil;
import com.ncloud.system.business.MenuBusi;
import com.ncloud.system.entity.Depart;
import com.ncloud.system.entity.Menu;
import com.ncloud.system.entity.User;
import com.ncloud.system.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by shiqiang on 2017/7/28.
 */
@Api(value = "自动化运维菜单管理", description = "菜单管理", tags = "菜单管理",
        basePath="/",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/sys")
public class MenuController {
    private final static Logger logger = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuBusi menuBusi;
    /*生成菜单*/
    @ApiOperation(value="create menu", notes="菜单创建：根据输入的菜单信息生成菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
            @ApiImplicitParam(name = "json", value = "菜单信息", required = true, dataType = "Menu" )
    })
    @PostMapping(value = "/menu")
    public Result<Object> saveMenu(HttpServletRequest request, @RequestBody Menu json) throws Exception {
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(2001,"用户ID不存在！");
        }else{
            json.setCreateUser(Long.parseLong(userID.toString()));
        }
        int num = menuService.insertMenu(json);
        return ResultUtil.success();
    }
    /*获取菜单列表*/
    @ApiOperation(value="getMenu", notes="根据登录用户获取当前用户下的菜单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/userMenu")
    public Result<JSONObject> getMenu(HttpServletRequest request) throws Exception {
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(2001,"用户ID不存在！");
        }
        //List<Menu> menus = menuService.getMenusByUser(Long.parseLong(userID.toString()));
        return ResultUtil.success(menuBusi.getUserMenu(Long.parseLong(userID.toString())));
    }
    /*获取可以看到的菜单列表*/
    @GetMapping(value = "/menu/viewMenu")
    public Result<List<Menu>> getviewMenu(HttpServletRequest request) throws Exception {
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(2001,"用户ID不存在！");
        }
        return ResultUtil.success(menuBusi.getViewMenu(Long.parseLong(userID.toString())));
    }
    /*获取菜单*/
    @ApiOperation(value="getMenu", notes="根据单个菜单id，获取菜单的详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/{menuId}")
    public Result<Menu> getMenu(@PathVariable("menuId") Long menuId,HttpServletRequest request) throws Exception {
       // Object userID = request.getAttribute("userID");
        Menu menu = menuService.getOneMenu(menuId);
        return ResultUtil.success(menu);
    }
    /*修改状态*/
    @ApiOperation(value="modifyMenuStatus", notes="根据单个菜单id和修改的状态，对菜单的状态进行操作")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @PutMapping(value = "/menu/{menuId}/{state}")
    public Result<Object> modifyMenuStatus(@PathVariable("menuId") Long menuId,@PathVariable("state") String state,
                                         HttpServletRequest request) throws Exception {
        int num = menuService.updateMenuState(state,menuId);
        return ResultUtil.success();
    }


    /*修改菜单信息*/
    @ApiOperation(value="修改菜单", notes="根据单个菜单id和修改的状态，对菜单的状态进行操作")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @PostMapping(value = "/menu/update")
    public Result<Object> modifyMenu(@RequestBody Menu json) throws Exception {
        int num = menuService.updateMenu(json);
        return ResultUtil.success();
    }
    /*校验同名菜单*/
    @ApiOperation(value="getSameName", notes="校验在同一个目录中的菜单，是否同名")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/sameName/{parentId}/{menuName}")
    public Result<Object> getSameName(@PathVariable("parentId") Long parentId,@PathVariable("menuName") String menuName,
                                    HttpServletRequest request) throws Exception {
        //Object userID = request.getAttribute("userID");
        Integer num = menuService.getSameMenuName(parentId,menuName);
        return ResultUtil.success(num);
    }
    /*校验同序菜单*/
    @ApiOperation(value="getSameName", notes="校验在同一个目录中的菜单，是否同序")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/sameOrder/{parentId}/{sort}")
    public Result<Object> getSameOrder(@PathVariable("parentId") Long parentId,@PathVariable("sort") Integer sort,
                                    HttpServletRequest request) throws Exception {
        //Object userID = request.getAttribute("userID");
        Integer num = menuService.getSameMenuOrder(parentId,sort);
        return ResultUtil.success(num);
    }

    /*修改菜单顺序*/
    @ApiOperation(value="updateMenuSort", notes="调整菜单的顺序，进行升序或降序")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @PostMapping(value = "/menu/sort")
    public Result<Object> updateMenuSort(HttpServletRequest request, @RequestBody JSONObject json) throws Exception {
        if(!json.containsKey("sortBy")){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"json字段属性{sortBy}不存在！");
        }
        menuService.updateMenuSort(json);
        return ResultUtil.success();
    }

    /*删除菜单*/
    @ApiOperation(value="deleteMenu", notes="根据菜单id删除菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @DeleteMapping(value = "/menu/{menuId}")
    public Result<Object> deleteMenu(HttpServletRequest request, @PathVariable("menuId") Long menuId) throws Exception {
        if(menuId == 0L){
            throw new UserException(ResultEnum.MENU_MASTER);
        }
        menuService.deleteMenu(menuId);
        return ResultUtil.success();
    }

    /*获取顶级菜单*/
    @ApiOperation(value="getMenusByTopLevel", notes="获取顶级菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/topLevel")
    public Result<List<Menu>> getMenusByTopLevel(HttpServletRequest request) throws Exception {
        List<Menu> menus = menuService.getMenusByLevel(0L);
        return ResultUtil.success(menus);
    }

    /*获取可选择菜单*/
    @ApiOperation(value="selectMenu", notes="获取可选择菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/selectMenu")
    public Result<List<Map<String,?>>> selectMenu(HttpServletRequest request) throws Exception {
        List<Map<String,?>> list = menuBusi.getSelectMenus();
        return ResultUtil.success(list);
    }

    /*获取可选择菜单*/
    @ApiOperation(value="selectMenuByRole", notes="获取已选择选择菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
    })
    @GetMapping(value = "/menu/allMenu/{roleId}")
    public Result<List<Map<String,Object>>> selectMenuByRole(@PathVariable("roleId") Long roleId) throws Exception {
        List<Map<String,Object>> list = menuBusi.getSelectMenusByRole(roleId);
        return ResultUtil.success(list);
    }
}
